package model

import (
	systemConfig "gin-worked/app/system/config"
	"gin-worked/dao"
	"gorm.io/gorm"
)

type DataSheet struct {
	Id           int    `json:"id"`
	Title        string `gorm:"column(title)" json:"title"`
	Type         string `gorm:"column(type)" json:"type"`
	Length       int    `gorm:"column(length)" json:"length"`
	Remark       string `gorm:"column(remark)" json:"remark"`
	DefaultValue string `gorm:"column(default_value)" json:"default_value"`
	ParentId     *int   `gorm:"default:0" json:"parent_id"`
	Status       int    `gorm:"column(status)" json:"status"`
	IsValidation int    `gorm:"column(is_validation)" json:"is_validation"`
	CreateTime   int    `gorm:"column(create_time)" json:"create_time"`
	UpdateTime   int    `gorm:"column(update_time)" json:"update_time"`
	DelTime      *int   `gorm:"default:0" json:"del_time"`
}

func DataSheetListAll(data *DataSheet, field []string, order string) ([]DataSheet, error) {

	var dataSheet []DataSheet
	err := dao.Db.Select(field).Where(data).Order(order).Find(&dataSheet).Error

	return dataSheet, err
}

// DataSheetAdd 添加数据表
func DataSheetAdd(data *DataSheet) (int, error) {
	err := dao.Db.Create(&data).Error
	return data.Id, err
}

// DataSheetInfo 详情
func DataSheetInfo(data *DataSheet, field []string) (DataSheet, error) {
	var dataSheet DataSheet
	err := dao.Db.Select(field).Where(data).First(&dataSheet).Error
	return dataSheet, err
}

func DataSheetEdit(data *DataSheet, content map[string]interface{}) error {
	err := dao.Db.Model(&data).Updates(content).Error
	return err
}

// SelectSql 获取数据库中的所有表名称
func SelectSql() []string {
	var tableNames []string
	dao.Db.Raw("SHOW TABLES").Scan(&tableNames)
	return tableNames
}

// SelectSqlField SelectSql 获取数据库中的所有表名称
func SelectSqlField(name string) []map[string]interface{} {
	filed, _ := dao.Db.Migrator().ColumnTypes(name) //获取以创建数据库字段
	filed1 := systemConfig.StructsToMap(filed)
	return filed1
}

func WorkAdd(db *gorm.DB, data *DataSheet) (int, error) {
	err := db.Create(&data).Error
	return data.Id, err
}
